<template>
  <el-dialog
    v-model="visible"
    :title="
      !isShowProd
        ? $t('product.select')
        : $t('product.viewProduct')
    "
    class="component-discount-add-or-update"
    :close-on-click-modal="false"
    :before-close="beforeClose"
  >
    <el-form
      :inline="true"
      :model="dataForm"
      class="demo-form-inline"
      @submit.prevent
    >
      <el-form-item :label="$t('product.prodName')">
        <el-input
          v-model="prodName"
          :placeholder="$t('product.prodName')"
          maxlength="60"
          show-word-limit
          clearable
        />
      </el-form-item>
      <el-form-item :label="$t('marketing.subHeadings')">
        <el-cascader
          v-model="selectedCategory"
          expand-trigger="hover"
          :options="categoryList"
          :props="categoryTreeProps"
          :clearable="true"
          @change="handleChange"
        />
      </el-form-item>
      <el-form-item>
        <div
          class="default-btn primary-btn"
          @click="searchProd"
        >
          {{
            $t("order.query")
          }}
        </div>
      </el-form-item>
      <el-form-item>
        <div
          class="default-btn"
          @click="clean"
        >
          {{
            $t("shop.resetMap")
          }}
        </div>
      </el-form-item>
    </el-form>
    <el-table
      ref="prodTable"
      v-loading="dataListLoading"
      :data="dataList"
      header-cell-class-name="table-header"
      row-class-name="table-row"
      style="width: 100%; margin-bottom: 20px"
    >
      <!-- <el-table-column v-if="!isShowProd"
                       type="selection"
                       header-align="center"
                       align="center"
                       width="50">
      </el-table-column>-->

      <el-table-column
        prop="prodName"
        :label="$t('product.prodName')"
      />
      <el-table-column
        align="center"
        width="140"
        :label="$t('product.pic')"
      >
        <template #default="scope">
          <prod-pic
            height="60px"
            width="60px"
            :pic="scope.row.pic"
          />
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      :current-page="pageIndex"
      :page-sizes="[10, 20, 50, 100]"
      :page-size="pageSize"
      :total="totalPage"
      layout="total, sizes, prev, pager, next, jumper"
      @size-change="sizeChangeHandle"
      @current-change="currentChangeHandle"
    />
    <template #footer>
      <span>
        <div
          :class="[dataListSelections.length <= 0 && isDistribution !== 102 && !isShowProd ? 'disabled-btn':'','default-btn primary-btn']"
          @click="selectProd()"
        >{{ $t("crud.filter.submitBtn") }}</div>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import { reactive } from 'vue'
const emit = defineEmits(['refreshDiscountProds'])

const props = defineProps({
  isDistribution: {
    default: false,
    type: Boolean
  }
})

const Data = reactive({
  visible: false,
  dataForm: {
    product: ''
  },
  isShowProd: 0,
  allData: [],
  prodId: 0,
  discountProds: [],
  discountId: 0,
  prodName: '',
  shopCategoryId: null,
  dataList: [],
  pageIndex: 1,
  pageSize: 10,
  totalPage: 0,
  dataListLoading: false,
  dataListSelections: [],
  addOrUpdateVisible: false,
  categoryList: [],
  selectedCategory: [],
  categoryTreeProps: {
    value: 'categoryId',
    label: 'categoryName'
  }
})

const { visible, dataForm, isShowProd, prodName, dataList, pageIndex, pageSize, totalPage, dataListLoading, dataListSelections, categoryList, selectedCategory, categoryTreeProps } = toRefs(Data)

// 获取数据列表
const init = (id, discountProds) => {
  Data.prodId = 0
  Data.discountProds = discountProds
  Data.discountId = id
  Data.visible = true
  Data.dataListLoading = true
  if (discountProds) {
    Data.discountProds.forEach(row => {
      Data.dataListSelections.push(row)
    })
  }
  getDataList()
  getCategoryList()
}

const getCategoryList = () => {
  http({
    url: http.adornUrl('/prod/category/listCategory'),
    method: 'get',
    params: http.adornParams({
      status: 1
    })
  }).then(({ data }) => {
    Data.categoryList = treeDataTranslate(data, 'categoryId', 'parentId')
  })
}

const showProdInit = (id, val) => {
  getCategoryList()
  Data.pageIndex = 1
  showProd(id, val)
}

const showProd = (id, val) => {
  Data.isShowProd = val
  Data.discountId = id
  Data.visible = true
  http({
    url: http.adornUrl(`/admin/discountProd/info/${id}`),
    method: 'get',
    params: http.adornParams({
      current: Data.pageIndex,
      size: Data.pageSize,
      prodName: Data.prodName ? Data.prodName : null,
      shopCategoryId: Data.shopCategoryId ? Data.shopCategoryId : null
    })
  }).then(({ data }) => {
    Data.dataList = data.records
    Data.totalPage = data.total
  })
}

const getDataList = () => {
  http({
    url: http.adornUrl('/prod/prod/pageOnLineProd'),
    method: 'get',
    params: http.adornParams({
      current: Data.pageIndex,
      size: Data.pageSize,
      prodName: Data.prodName ? Data.prodName : null,
      shopCategoryId: Data.shopCategoryId ? Data.shopCategoryId : null,
      status: 1,
      isDistribution: props.isDistribution ? 1 : 0
    })
  }).then(({ data }) => {
    Data.dataList = data.records
    Data.totalPage = data.total
    Data.dataListLoading = false
    nextTick(() => {
      if (Data.discountProds) {
        Data.discountProds.forEach(row => {
          const index = Data.dataList.findIndex(
            prodItem => prodItem.prodId === row.prodId
          )
          Data.$refs.prodTable.toggleRowSelection(Data.dataList[index])
        })
      }
    })
  })
}

// 每页数
const sizeChangeHandle = (val) => {
  Data.pageSize = val
  Data.pageIndex = 1
  if (props.isDistribution) {
    getDataList()
  } else {
    showProd(Data.discountId, Data.discountProds)
  }
}

// 当前页
const currentChangeHandle = (val) => {
  Data.pageIndex = val
  if (props.isDistribution) {
    getDataList()
  } else {
    showProd(Data.discountId, Data.discountProds)
  }
}

/**
     * 获取分类id
     */
const handleChange = (val) => {
  Data.shopCategoryId = val[val.length - 1]
}

/**
     * 根据条件搜索商品
     */
const searchProd = () => {
  Data.pageIndex = 1
  if (props.isDistribution) {
    getDataList()
  } else {
    showProd(Data.discountId, Data.discountProds)
  }
}

/**
     * 清空搜索条件
     */
const clean = () => {
  Data.prodName = ''
  Data.shopCategoryId = null
  Data.selectedCategory = idList(Data.categoryList, Data.shopCategoryId, 'categoryId', 'children').reverse()
}

// 关闭页面操作
const beforeClose = (done) => {
  clean()
  done()
}

// 选择产品
const selectProd = () => {
  if (Data.isShowProd) {
    clean()
    Data.visible = false
    return
  }
  if (Data.dataListSelections.length <= 0 && props.isDistribution !== 102) {
    return
  }
  const prods = []
  Data.dataListSelections.forEach(item => {
    const prodIndex = prods.findIndex(prod => prod.prodId === item.prodId)
    if (prodIndex === -1) {
      prods.push({
        discountProdId: 0,
        prodId: item.prodId,
        prodName: item.prodName,
        pic: checkFileUrl(item.pic)
      })
    }
  })
  // var prods = Data.dataListSelections.map(item => {
  //   return {discountProdId: 0, prodId: item.prodId, prodName: item.prodName, pic: item.pic}
  // })
  emit('refreshDiscountProds', prods)
  Data.dataListSelections = []
  clean()
  Data.visible = false
}

defineExpose({
  init,
  showProdInit
})
</script>

<style lang="scss" scoped>

</style>
